package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.exceptor.BusinessException;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //分页查询评论列表
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        // 1 调用api查询评论列表
        List<Comment> list =  commentApi.findComments(movementId, CommentType.COMMENT,page,pagesize);

        // 2 判断list 集合是否存在
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }

        // 3 提取所有的用户id 调用UserInfoApi 查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo>  map = userInfoApi.findByIds(userIds, null);

        // 4 构造vo对象
        ArrayList<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }

        // 5 构造返回值
        return new PageResult(page,pagesize,0L,vos);

    }

    /**
     * 发布评论
    * */
    public void saveComments(String movementId, String comment) {
        // 获取发布评论人的id
        Long userId = UserHolder.getUserId();

        // 构造评论实体类对象
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());

        // 调用api 保存品论
       Integer commentCount =  commentApi.save(comment1);
       log.info("commentCount = " + commentCount     );
    }

    //动态点赞
    public Integer likeComment(String movementId) {
        // 查询用户是否已经给该动态点过赞 如果已经点赞抛出异常
        Boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LIKE);

        if (hasComment) {
            throw   new BusinessException(ErrorResult.likeError());
        }

        // 保存品论信息到MongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //拼接 redis 的key 将 用户的点赞状态 存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;

    }

    //取消点赞
    public Integer dislikeComment(String movementId) {
        // 查看是否已经点赞 如果没有点赞 则抛出异常
        Boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LIKE);
        if (!hasComment){
            throw new BusinessException(ErrorResult.disLikeError());
        }

        // 删除mongoDB中 对应的品论信息 返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.delete(comment);

        // 拼接 redis 的 key 删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;

    }

    /**
    * 喜欢
    * */
    public Integer loveComment(String movementId) {
        //查询 是否已经点了 喜欢  重复点击则抛出异常
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        if (hasComment){
            throw new BusinessException(ErrorResult.loveError());
        }
        // 将数据保存到MongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.save(comment);

        // 拼接redis 将用户的点赞状态 存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY+movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY +UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey,"1");
        return count    ;
    }

    /**
     * 取消喜欢
     * */
    public Integer disloveComment(String movementId) {
        // 查看 自己是否已经取消 喜欢 已经取消则抛出异常
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        if (!hasComment){
            throw new BusinessException(ErrorResult.disloveError());
        }

        // 调用api 删除数据 返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.delete(comment);

        // 拼接redis的key 删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
}
